const fs = require("fs");
const path = require("path");
const user = require("../sql/user");
const sql = require("../sql/index");

module.exports = function(){
    return (req, res, next)=>{
        // 接收到前端发送的数据后，处理数据成集合所需格式
        // console.log(req.body);
        // console.log(req.files);
        const obj = req.body;
        obj.tel -= 0;
        obj.hobby = obj.hobby.split(/,|\uff0c/);

        // 拼接头像文件路径，用于修改头像文件名
        const oldName = path.join(__dirname, "..", req.files[0].path);
        const newName = oldName + "-" + req.files[0].originalname;
        fs.renameSync(oldName, newName);
        
        // 拼接头像文件的服务器地址
        // http://localhost:3000/xxxxxx.jpg
        // file:///users/liyang/desktop/sh2205/code/day26/upload/xxx-img1.jpg
        const serverUrl = "http://localhost:3000" + newName.split("upload")[1];
        
        obj.avatar = serverUrl;
        // 根据userid修改，获取到的要修改的用户数据
        sql.set(user, {userid: req.body.userid}, obj, ()=>{
            res.send(JSON.stringify({
                code:1,
                msg:"修改成功"
            }));
        })
    }
}